<script setup lang="ts">
import { ref, nextTick, onMounted } from "vue";
import { warning, success } from "@/message/messageApi";
import { marked } from "marked";
import axios from "axios";
import { v4 as uuidv4 } from 'uuid';
import hljs from 'highlight.js';
//import 'highlight.js/styles/github.css';
import 'highlight.js/styles/atom-one-dark.css';
import DOMPurify from "dompurify";
// 定义消息类型
interface ChatMessage {
  sessionId: string;
  role: string;
  part: string;
  isThinking?: boolean;
}

// 定义对话类型
interface Conversation {
  sessionId: string;
  title: string;
  messages: ChatMessage[];
  lastActive: number;
}

// 响应式变量
const inputValue = ref('');
const conversations = ref<Conversation[]>([]);
const currentConversationId = ref<string>('');
const isSending = ref(false);
const isShow = ref(true);
// 配置marked以支持代码高亮

marked.setOptions({
  breaks: true,
  gfm: true,
  highlight: function(code, lang) {
    if (lang && hljs.getLanguage(lang)) {
      return hljs.highlight(lang, code).value;
    }
    return hljs.highlightAuto(code).value;
  },
});

// 渲染 AI 消息（允许代码高亮，但净化 HTML）
const renderMarkdown = (text: string) => {
  const rawHtml = marked(text);
  return DOMPurify.sanitize(rawHtml);
};

// 渲染用户消息（禁用代码高亮，并转义 HTML）
const renderUserMarkdown = (text: string) => {
  const escapedText = text
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;");
  return marked(escapedText, {
    breaks: true,
    gfm: true,
    highlight: null, // 禁用代码高亮
  });
};

// 获取当前对话
const currentConversation = ref<Conversation | null>(null);

// 生成新的会话ID
function generateConversationId() {
  return uuidv4();
}

// 创建新对话
function createNewConversation() {
  const newSessionId = generateConversationId();
  const newConversation: Conversation = {
    sessionId: newSessionId,
    title: '新对话',
    messages: [],
    lastActive: Date.now()
  };

  conversations.value.unshift(newConversation);
  switchConversation(newSessionId);
  //success("已创建新对话");
}

// 切换对话
function switchConversation(sessionId: string) {
  const conversation = conversations.value.find(c => c.sessionId === sessionId);
  if (conversation) {
    currentConversationId.value = sessionId;
    currentConversation.value = conversation;
    isShow.value = conversation.messages.length === 0;
  }
}

// 更新对话标题（基于第一条消息）
function updateConversationTitle(sessionId: string, firstMessage: string) {
  const conversation = conversations.value.find(c => c.sessionId === sessionId);
  if (conversation) {
    // 取前20个字符作为标题
    conversation.title = firstMessage.length > 20
      ? firstMessage.substring(0, 20) + '...'
      : firstMessage;
    conversation.lastActive = Date.now();

    // 按照最后活跃时间排序
    conversations.value.sort((a, b) => b.lastActive - a.lastActive);
  }
}

// 发送消息函数
async function sendMessage() {
  if (!inputValue.value.trim()) {
    warning("请输入内容");
    return;
  }

  if (!currentConversation.value) {
    createNewConversation();
    await nextTick();
  }

  isShow.value = false;

  if (isSending.value) {
    warning("正在处理上一条消息，请稍候...");
    return;
  }

  isSending.value = true;

  try {
    // 如果是新对话且没有标题，使用第一条消息作为标题
    if (currentConversation.value && currentConversation.value.title === '新对话') {
      updateConversationTitle(currentConversationId.value, inputValue.value.trim());
    }

    // 添加用户消息
    const userMessage: ChatMessage = {
      sessionId: currentConversationId.value,
      role: "user",
      part: inputValue.value.trim(),
    };
    currentConversation.value?.messages.push(userMessage);

    // 添加AI消息，初始状态为思考中
    const aiMessage: ChatMessage = {
      sessionId: currentConversationId.value,
      role: "assistant",
      part: "",
      isThinking: true
    };
    currentConversation.value?.messages.push(aiMessage);
    scrollToBottom();

    const data = {
      memoryId: currentConversationId.value,
      question: encodeURIComponent(inputValue.value.trim()),
      username: localStorage.getItem("uid")
    }

    const res = await fetch(
      `http://127.0.0.1:8888/ai/chat2?memoryId=${currentConversationId.value}
      &question=${encodeURIComponent(inputValue.value.trim())}
      &username=${localStorage.getItem("uid")}`,
      {
        method: "GET"
      },
    );
    inputValue.value = "";

    if (!res.body) {
      throw new Error("Response body is null");
    }

    const reader = res.body.getReader();
    const decoder = new TextDecoder("utf-8");
    let done = false;
    const aiResponseIndex = currentConversation.value?.messages.length ? currentConversation.value.messages.length - 1 : 0;

    // 开始接收响应后，取消思考状态
    if (currentConversation.value?.messages[aiResponseIndex]) {
      currentConversation.value.messages[aiResponseIndex].isThinking = false;
    }

    while (!done) {
      const { value, done: readDone } = await reader.read();
      done = readDone;

      if (value) {
        const chunk = decoder.decode(value, { stream: true });
        if (currentConversation.value?.messages[aiResponseIndex]) {
          currentConversation.value.messages[aiResponseIndex].part += chunk;
        }
        await nextTick();
      }
      scrollToBottom();
    }
  } catch (err) {
    console.error("请求失败:", err);
    if (currentConversation.value?.messages) {
      currentConversation.value.messages.pop();
    }
    warning("无法获取AI响应，请稍后重试");
  } finally {
    isSending.value = false;
    scrollToBottom();
  }
}
// bug
// 滚动到底部的函数
function scrollToBottom() {
  const messageContainer = document.querySelector(".message-container");
  if (messageContainer) {
    messageContainer.scrollTop = messageContainer.scrollHeight;
  }
}

// 获取用户聊天历史记录
async function getUserChatHistoryMessage() {
  try {
    const response = await axios.get(
      `http://localhost:8888/ai/getChatHistoryMessage?username=${localStorage.getItem("uid")}`
    );

    const resData = response.data.data;
    if (resData.length > 0) {
      isShow.value = false;

      // 将服务器返回的对话数据转换为前端格式
      resData.forEach(session => {
        const messages: ChatMessage[] = [];

        session.msg.forEach(msgItem => {
          if (msgItem.type === "USER") {
            const userContent = msgItem.contents[0].text;
            messages.push({
              sessionId: session.sessionId,
              role: "user",
              part: userContent
            });
          } else if (msgItem.type === "AI") {
            const aiContent = msgItem.text;
            messages.push({
              sessionId: session.sessionId,
              role: "assistant",
              part: aiContent
            });
          }
        });

        // 创建对话对象
        const conversation: Conversation = {
          sessionId: session.sessionId,
          title: messages[0]?.part ?
            (messages[0].part.length > 20
              ? messages[0].part.substring(0, 20) + '...'
              : messages[0].part)
            : '无标题对话',
          messages: messages,
          lastActive: session.lastActive || Date.now()
        };

        conversations.value.push(conversation);
      });

      // 按照最后活跃时间排序
      conversations.value.sort((a, b) => b.lastActive - a.lastActive);

      // 默认显示第一个对话
      if (conversations.value.length > 0) {
        switchConversation(conversations.value[0].sessionId);
      }
    }
  } catch (error) {
    console.error("获取聊天记录失败:", error);
  }
}

// 删除对话
async function deleteConversation(sessionId: string, event: Event) {
  event.stopPropagation();
  console.log(sessionId)
  try {
    await axios.delete(
      `http://127.0.0.1:8888/ai/deleteConversation?sessionId=${sessionId}&username=${localStorage.getItem("uid")}`
    );

    // 从本地列表中移除
    conversations.value = conversations.value.filter(c => c.sessionId !== sessionId);

    // 如果删除的是当前对话，切换到其他对话或创建新对话
    if (currentConversationId.value === sessionId) {
      if (conversations.value.length > 0) {
        switchConversation(conversations.value[0].sessionId);
      } else {
        createNewConversation();
      }
    }

    success("对话已删除");
  } catch (error) {
    console.error("删除对话失败:", error);
    warning("删除对话失败，请重试");
  }
}

// 组件挂载时加载聊天记录
onMounted(() => {
  getUserChatHistoryMessage();

  // 如果没有历史记录，创建一个新对话
  setTimeout(() => {
    if (conversations.value.length === 0) {
      createNewConversation();
    }
  }, 500);
});
</script>

<template>
  <div class="common-layout">
    <el-container>
      <el-aside width="230px" style="height: 100vh; display: flex; flex-direction: column;">
        <div style="display: flex; justify-content: center; padding: 15px; flex-shrink: 0;">
          <el-button type="primary" round @click="createNewConversation" style="width: 200px; height: 50px">
            新建对话
            <el-icon class="plus-icon">
              <Plus/>
            </el-icon>
          </el-button>
        </div>
        <div class="sidebar-container">
          <div class="sidebar-list">
            <div
              v-for="conversation in conversations"
              :key="conversation.sessionId"
              class="sidebar-title"
              :class="{ active: currentConversationId === conversation.sessionId }"
              @click="switchConversation(conversation.sessionId)"
            >
              <!--聊天标题-->
              <span class="title-text">{{ conversation.title }}</span>
              <!--              <span>{{ conversation.title }}</span>-->
              <el-icon class="delete-icon" @click.stop="deleteConversation(conversation.sessionId, $event)">
                <Delete />
              </el-icon>
            </div>
          </div>
        </div>
      </el-aside>
      <el-container>
        <el-main>
          <div class="chat">
            <!-- 消息历史记录 -->
            <div class="message-container">
              <template v-if="currentConversation">
                <div
                  v-for="(item, index) in currentConversation.messages"
                  :key="index"
                  class="message-item"
                >
                  <div class="avatar">
                    <img
                      v-if="item.role === 'user'"
                      src="../../../assets/images/my.jpg"
                      alt="user"
                      width="50px"
                      style="border-radius: 50%"
                    />
                    <img
                      v-else
                      src="../../../assets/images/aipro.webp"
                      width="50px"
                      alt="ai"
                      style="border-radius: 50%"
                    />
                  </div>
                  <div class="content">
                    <!-- Thinking indicator -->
                    <div v-if="item.isThinking" class="thinking-indicator">
                      <div class="dot"></div>
                      <div class="dot"></div>
                      <div class="dot"></div>
                    </div>
                    <!-- User message (plain text) -->
                    <div v-else-if="item.role === 'user'" class="user-message">
                      <div v-html="renderUserMarkdown(item.part)"></div>
                    </div>
                    <!-- AI message (markdown rendered) -->
                    <div v-else>
                      <div v-html="renderMarkdown(item.part)" class="markdown-content"></div>
                      <el-text>{{new Date().toLocaleDateString()}}</el-text>
                    </div>

                  </div>
                </div>
              </template>

              <div v-if="isShow === true" style="margin: 150px 0 0 -100px;">
                <div style="display: flex; justify-content: center; align-items: center; text-align: center;">
                  <div style="display: flex; align-items: center; gap: 10px;">
                    <img src="../../../assets/images/ai.svg" width="60">
                    <h3 style="margin: 0;">我是 DeepSeek，很高兴见到你！</h3>
                  </div>
                </div>
                <div style="text-align: center; margin-top: 20px;">
                  我可以帮你写代码、读文件、写作各种创意内容，请把你的任务交给我吧~
                </div>
              </div>
            </div>
          </div>
        </el-main>
        <el-footer style="display: flex;justify-content: center;height: 100px">
          <div>
            <div class="send-box">
              <textarea
                v-model="inputValue"
                placeholder="发送消息"
                rows="2"
                @keydown.enter.exact.prevent="sendMessage"
                @keydown.shift.enter.exact="inputValue += '\n'"
              ></textarea>
              <button :disabled="isSending" @click="sendMessage">
                {{ isSending ? "发送中..." : "发送" }}
              </button>
            </div>
          </div>
        </el-footer>
        <div class="footer">
          <text>
            服务生成的所有内容均由人工智能模型生成，其生成内容的准确性和完整性无法保证，不代表我们的态度或观点
          </text>
        </div>
      </el-container>
    </el-container>
  </div>
</template>

<style >
.common-layout{
  display: flex;
  height: calc(100vh - 10% - 50px);
}

.chat {
  display: flex;
  align-items: center;
  justify-items: center;
  flex-direction: column;
  height: calc(100vh - 10% - 280px);
  padding: 16px;

}

.sidebar-container {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;

}

.sidebar-list {
  display: flex;
  flex-direction: column;
  padding: 0 15px 15px;
  width: 200px;
  overflow-y: auto;
  flex: 1;
  gap: 10px;
  transition: 1.5s;
}

.sidebar-title {
  height: 38px;
  min-width: 200px;
  max-width: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #ffffff;
  border-radius: 10px;
  padding: 0 10px;
  flex-shrink: 0;
  cursor: pointer;
  box-sizing: border-box;
  transition: 1.5s;
}

.title-text {
  display: inline-block;
  width: 180px; /* 固定文本宽度 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 15px;
  text-align: left;
}

.sidebar-title:hover {
  background-color: #deeaf8;
  border-radius: 10px;
  color: #ffffff;
  transition: all 0.3s ease;
}

/* 当前选中对话的样式 */
.sidebar-title.active {
  background-color: #deeaf8;
  color: #ffffff;
}

.message-container {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 16px;
}

.message-item {
  width: 950px;
  display: flex;
  align-items: flex-start;
  margin-bottom: 16px;
}

.avatar {
  margin-right: 12px;
}

.content {
  display: flex;
  justify-content: center;
  padding: 18px 0;
}

.content text{
  justify-content: center;
  align-items: center;
}

.send-box {
  display: flex;
  width: 1000px;
  gap: 8px;
  position: sticky;
  bottom: 0;
  background-color: white;
  padding: 4px 0;
  border-radius: 10px;
  box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
}

textarea {
  flex: 1;
  padding: 12px;
  border: 1px solid #ccc;
  border-radius: 10px;
  resize: none;
  font-size: 20px;
}
textarea::placeholder {
  font-size: 20px;
  align-items: center;
}
textarea:focus {
  border-color: #409eff;
  outline: none;
  box-shadow: 0 0 5px rgba(64, 158, 255, 0.5);
}

button {
  padding: 8px 16px;
  background-color: #007bff;
  color: white;
  border: none;
  width: 90px;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #0056b3;
}

.footer {
  display: flex;
  justify-content: center;
  margin-top: auto;
}

.footer text {
  font-size: 9px;
  color: #bdbec1;
}
.message-container {
  width: 1000px;
  overflow-y: auto;
  margin-bottom: 16px;
  scroll-behavior: smooth;
}

/* 思考指示器样式 */
.thinking-indicator {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 12px;
}

.dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #888;
  animation: bounce 1.4s infinite ease-in-out;
}

.dot:nth-child(1) {
  animation-delay: -0.32s;
}

.dot:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes bounce {
  0%, 80%, 100% {
    transform: scale(0);
  } 40% {
      transform: scale(1);
    }
}

.markdown-content{
  font-size: 16px;
  background: white;
  border-radius: 15px;
  padding: 4px 15px;
  /*padding: 14px;*/
  /*background-color: #cbcaca;*/
}
.user-message{
  background: white;
  border-radius: 15px;
  padding: 4px 15px;
  font-size: 16px;
  /*font-weight: bolder;*/
  color: #525252;
  /*background-color: #de970a;*/
}


.markdown-content h1, .markdown-content h2, .markdown-content h3 {
  color: #333;
}

.content .markdown-content think pre code {
  background: #f4f4f4;
  padding: 2px 4px;
  border-radius: 4px;
}

.delete-icon {
  opacity: 0;
  transition: opacity 0.3s ease;
}

.delete-icon:hover {
  opacity: 1;
}

.markdown-content {
  font-size: 16px;
  border-radius: 15px;
  padding: 15px;
}

/* 代码块样式 */
.markdown-content pre {
  background-color: #eae9e9 !important;
  border-radius: 6px !important;
  padding: 16px !important;
  margin: 12px 0 !important;
  overflow-x: auto;
}

.markdown-content code:not(pre code) {
  background-color: transparent !important;
  padding: 2px 4px;
  border-radius: 4px;
}

.markdown-content pre code {
  background-color: transparent !important;
  color: inherit !important;
  padding: 0 !important;
}

/* 确保行号和代码对齐 */
.markdown-content .hljs {
  display: block;
  overflow-x: auto;
  padding: 1em;
}
</style>
